from rest_framework.views import APIView
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, CreateAPIView
from rest_framework.response import Response
from django.utils import timezone
from django.conf import settings
from blogapi.models import *
from blogapi.serializers import *
from blogapi.service.utils import ResBody
import logging
import os
import time
import re
# import random
# from string import ascii_lowercase

logger = logging.getLogger(__name__)


class GetNow(APIView):
    name = 'now'

    def get(self, request: object):
        res = ResBody()
        res.update(data=timezone.now())
        return Response(data=res.data)


class TagsListCreate(ListCreateAPIView):
    queryset = Tag.objects.all()
    serializer_class = TagsSerializer
    name = 'tags_lc'


class TagsRetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):
    queryset = Tag.objects.all()
    serializer_class = TagsSerializer
    name = 'tags_sud'


class CategoriesListCreate(ListCreateAPIView):
    queryset = Category.objects.all()
    serializer_class = CategoriesSerializer
    name = 'categories_lc'


class CategoriesRetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):
    queryset = Category.objects.all()
    serializer_class = CategoriesSerializer
    name = 'categories_sud'


class AuthorsListCreate(ListCreateAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorsSerializer
    name = 'authors_lc'


class AuthorsRetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorsSerializer
    name = 'authors_sud'


class ArticalsListCreate(ListCreateAPIView):
    queryset = Artical.objects.all()
    serializer_class = ArticalsSerializer
    name = 'articals_lc'


class ArticalsRetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):
    queryset = Artical.objects.all()
    serializer_class = ArticalsSerializer
    name = 'articals_sud'


class RArticalTagCreate(CreateAPIView):
    queryset = RArticalTag.objects.all()
    serializer_class = RArticalTagCreateSerializer
    name = 'rarticaltag_create'


class RArticalTagRetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):
    queryset = RArticalTag.objects.all()
    serializer_class = RArticalTagCreateSerializer
    name = 'rarticaltag_sud'


class RArticalAuthorCreate(CreateAPIView):
    queryset = RArticalAuthor.objects.all()
    serializer_class = RArticalAuthorCreateSerializer
    name = 'rarticalauthor_create'


class RArticalAuthorRetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):
    queryset = RArticalAuthor.objects.all()
    serializer_class = RArticalAuthorCreateSerializer
    name = 'rarticalauthor_sud'


class RArticalCategoryCreate(CreateAPIView):
    queryset = RArticalCategory.objects.all()
    serializer_class = RArticalCategoryCreateSerializer
    name = 'r_artical_category_create'


class RArticalCategoryRetrieveUpdateDelete(RetrieveUpdateDestroyAPIView):
    queryset = RArticalCategory.objects.all()
    serializer_class = RArticalCategoryCreateSerializer
    name = 'r_artical_category_sud'


class GetMarkdownSource(APIView):
    name = 'get_markdown_source'

    def get(self, request, filename):
        res = ResBody()
        base_path = r'/datageek/DataGeek/markdown'
        with open(os.path.join(base_path, filename), mode='r') as file:
            content = ''.join(file.readlines())
            res.update(data=content)
        return Response(data=res.data)


class ArticalUpload(APIView):
    name = 'artical_upload'

    def post(self, request):
        res = ResBody()
        data = request.data
        file = data['file']
        html_dir = settings.HTML_DIR
        if not os.path.isdir(html_dir):
            os.mkdir(html_dir)
        try:
            filename = file.name
            # filename = ''.join(random.choices(population=ascii_lowercase, k=5)) + '.md'
            full_path = os.path.join(html_dir, filename)
            with open(full_path, mode='wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)
        except Exception as e:
            raise e
        else:
            res.update(data={'path': full_path})
            # new_artical = Artical(title=file.name, html_path=full_path)
            # new_artical.save()
        return Response(data=res.data)


class Mdlist(APIView):
    name = 'md_list'

    def get(self, request):
        res = ResBody()
        upload_dir = settings.MD_DIR
        filename_list = os.listdir(upload_dir)
        data = tuple(map(self.format_results, filename_list))
        res.update(data=data)
        return Response(data=res.data)

    def format_results(self, item):
        seconds = os.path.getmtime(os.path.join(settings.MD_DIR, item))
        return {
            'filename': item,
            'updatets': time.strftime('%Y-%m-%d %H:%M', time.localtime(seconds))
        }


class MdItem(APIView):
    name = 'md_item'

    def get(self, request, filename):
        res = ResBody()
        upload_dir = settings.MD_DIR
        with open(os.path.join(upload_dir, filename), mode='r', encoding='UTF-8') as file:
            content = ''.join(file.readlines())
            res.update(data=content)
        return Response(data=res.data)


class HTMLList(APIView):
    name = 'html_list'

    def get(self, request):
        res = ResBody()
        html_dir = settings.HTML_DIR
        filename_list = os.listdir(html_dir)
        filename_list = filter(lambda item: item.endswith('.html'), filename_list)
        data = tuple(map(self.format_results, filename_list))
        res.update(data=data)
        return Response(data=res.data)

    def format_results(self, item):
        seconds = os.path.getmtime(os.path.join(settings.HTML_DIR, item))
        filename = re.sub(pattern=r'\.[^\.]+$', repl='', string=item)
        return {
            'filename': filename,
            'updatets': time.strftime('%Y-%m-%d %H:%M', time.localtime(seconds))
        }


class HTML(APIView):
    name = 'html'

    def get(self, request, filename):
        res = ResBody()
        html_dir = settings.HTML_DIR
        filename += '.html'
        with open(os.path.join(html_dir, filename), mode='r', encoding='UTF-8') as file:
            content = ''.join(file.readlines())
            res.update(data=content)
        return Response(data=res.data)
